import { omit } from "lodash";
import { PassThrough } from "node:stream";
import getChatGptAnswerStream, {
  IChatArgs,
} from "../../../apis/chatGpt/get_chatGpt_answer";
import { removeUndefinedKeys } from "../../../util";

export default async function getChatGptAnswer(
  ctx: Context,
  next: Next
): Promise<IAnyObject> {
  // 响应头
  const responseHeaders = { "Content-Type": "text/event-stream" };

  try {
    const queryInfo = ctx.request.body as IAnyObject;

    // 格式化参数
    const args = removeUndefinedKeys({
      api: queryInfo?.api || "createChatCompletion", // 使用那种模式，默认使用对话
      args: {
        ...omit(queryInfo, "api", "option", "apikey"),
        model: queryInfo.model || "gpt-3.5-turbo", // 没有就默认使用聊天模型
      }, // 这个key之后从数据库读取，只需要第一次传入 TODO
      options: queryInfo?.option as never,
    }) as IChatArgs;

    // 是否是流式处理
    const result = new PassThrough();

    const response = await getChatGptAnswerStream(args);
    const data = response?.data;

    // 数据流失监听
    data.on("data", (chunk: any) => {
      result.write(chunk.toString());
    });
    data.on("end", () => {
      result.end();
    });

    ctx.api.success(result, "success", responseHeaders);
  } catch (error) {
    const err = error.message || "unkown error";
    ctx.api.fail(-1, err);
  }

  return next();
}
